<style lang="less">
    .category-tree {
        & {
            width: 100%;
            // padding-bottom: 200px;
            min-height: 500px;
            overflow: auto;
        }
        .divider {
            margin-left: 4px;
            margin-right: 4px;
        }
    }
</style>
<template>
    <div class="category-tree">
        <a-tree :default-expand-all="false" :blockNode="true" :selected-keys="selectedKeys" :tree-data="treeData" :expandedKeys="expandedKeys" :draggable="false" @select="onTreeSelect" @expand="onExpand">
            <template slot="custom" slot-scope="item">
                <div v-if="hasOper">
                    <div v-if="!item.isRoot">
                        <span>{{item.title}} </span>
                        <zk-btn @click.stop="addNode(item)">新增</zk-btn>
                        <a-divider type="vertical" class="divider"/>
                        <zk-btn @click.stop="showNodeDetail(item)">查看</zk-btn>
                        <a-divider type="vertical" class="divider" />
                        <zk-btn @click.stop="showNodeEdit(item)">修改</zk-btn>
                        <a-divider type="vertical" class="divider" />
                        <zk-btn @click.stop="delNode(item)">删除</zk-btn>
                        <a-divider type="vertical" class="divider" v-if="!item.isFirst" />
                        <zk-btn @click.stop="upNode(item)" v-if="!item.isFirst">上移</zk-btn>
                        <a-divider type="vertical" class="divider" v-if="!item.isLast" />
                        <zk-btn @click.stop="downNode(item)" v-if="!item.isLast">下移</zk-btn>
                    </div>
                    <div v-else>
                        <span>{{item.title}} </span>
                        <zk-btn @click.stop="addNode(item)">新增</zk-btn>
                    </div>
                </div>
                <div v-else>
                    <span>{{item.title}} </span>
                </div>
            </template>
        </a-tree>
        <EditVue ref="edit"></EditVue>
        <DetailVue ref="detail"></DetailVue>
    </div>
</template>
<script>
    import { delCategoryTreeNode, queryCategoryTree, updateCategoryTreeNodeSort } from '@/api/common';
    import EditVue from './category/Edit.vue';
    import DetailVue from './category/Detail.vue';
    import { updateChapterSort } from '@/api/resourcesPool';
    export default {
        components: {
            EditVue,
            DetailVue
        },
        props: {
            /** 1-产教融合新闻 2-社区公共服务内容 3-社群公共服务视频(废弃) 4-资源库 105.课程章节 5.试题库 6.试卷 7.考试 */
            type: {
                type: Number,
                require: true
            },
            /** 是否有操作功能 */
            hasOper: {
                type: Boolean,
                default: () => false
            },
            title: {
                type: String,
                default: () => null
            },
            rootKey: {
                type: String,
                default: () => '0'
            }
        },
        data() {
            return {
                // 选中的
                selectedKeys: [],
                // 状态树
                treeData: [],
                // 展开的树节点
                expandedKeys: [],
            }
        },
        async created() {
            await this.refresh();
            this.expandedKeys = [this.rootKey];
        },
        methods: {
            async refresh() {
                let arr =  await queryCategoryTree({ type: this.type }) || [];
                let title = this.title;
                if (this.type == 4) {
                    title = '所有资源'
                } else if (this.type == 3) {
                    title = '所有视频'
                } else if (this.type == 1) {
                    title = '产教融合新闻'
                } else if (this.type == 2) {
                    title = '培训集团'
                } else if (this.type == 5) {
                    title = '所有试题'
                } else if (this.type == 6) {
                    title = '所有试卷'
                } else if (this.type == 7) {
                    title = '所有考试'
                } 


                this.treeData = [
                    {
                        title,
                        key: this.rootKey,
                        scopedSlots: {
                            title: 'custom',
                        },
                        isRoot: true,
                        children: nodeDataToVMNodeData(arr)
                    }
                ];
            },
            onTreeSelect(selectedKeys, e) {
                this.setTreeSelected(selectedKeys);
                if (e.selected) {
                    this.$emit('selected', e.node.dataRef);
                } else {
                    this.$emit('selected', null);
                }
            },
            onExpand(expandedKeys) {
                this.expandedKeys = expandedKeys;
            },
            setTreeSelected(selectedKeys) {
                this.selectedKeys = [...selectedKeys];
                if (selectedKeys.length > 0 && selectedKeys[0] == 0) {
                    selectedKeys[0] = null;
                }
            },

            addNode(item) {
                this.$refs.edit.show({
                    parentId: item.key == this.rootKey ? '0' : item.key,
                    parentName: item.title,
                    type: this.type,
                    onOk: async () => {
                        await this.refresh();
                        this.expandedKeys.push(item.key);
                    }
                });
            },
            showNodeDetail(item) {
                this.$refs.detail.show({
                    id: item.key
                });
            },
            showNodeEdit(item) {
                this.$refs.edit.show({
                    id: item.key,
                    onOk: async () => {
                        await this.refresh();
                    }
                });
            },
            delNode(item) {
                if (item.children && item.children.length > 0) {
                    this.$warning({
                        title: '提示',
                        content: `当前分类包含下级分类，不可被删除！`
                    })
                    return;
                }
                this.$confirm({
                    title: '提示',
                    content: `确定要删除当前分类？`,
                    onOk: async () => {
                        await delCategoryTreeNode({ id: item.id });
                        await this.refresh();
                    }
                });
            },
            async upNode(item) {
                const res = queryNodeInTree(item.key, { children: this.treeData });
                if (!res) {
                    throw Error('未找到节点！', item);
                }
                const arr = res.pNode.children;
                const index = arr.findIndex(i => i.key == item.key);
                const node = arr[index];
                const preNode = arr[index - 1];
                    await updateCategoryTreeNodeSort({
                        maxId: node.key,
                        maxSortNo: node.sortNo,
                        minId: preNode.key,
                        minSortNo: preNode.sortNo
                    });
                // 对调两节点位置
                let { isFirst, isLast } = preNode;
                preNode.isFirst = node.isFirst;
                preNode.isLast = node.isLast;
                node.isFirst = isFirst;
                node.isLast = isLast;
                arr[index] = preNode;
                arr[index - 1] = node;
                this.expandedKeys = [...this.expandedKeys];
            },
            async downNode(item) {
                const res = queryNodeInTree(item.key, { children: this.treeData });
                if (!res) {
                    throw Error('未找到节点！', item);
                }
                const arr = res.pNode.children;
                const index = arr.findIndex(i => i.key == item.key);
                const node = arr[index];
                const nextNode = arr[index + 1];
             
                    await updateCategoryTreeNodeSort({
                        maxId: nextNode.key,
                        maxSortNo: nextNode.sortNo,
                        minId: node.key,
                        minSortNo: node.sortNo
                    });


                // 对调两节点位置
                let { isFirst, isLast } = nextNode;
                nextNode.isFirst = node.isFirst;
                nextNode.isLast = node.isLast;
                node.isFirst = isFirst;
                node.isLast = isLast;
                arr[index] = nextNode;
                arr[index + 1] = node;
                this.expandedKeys = [...this.expandedKeys];
            }
        }
    }
    /**
     * 节点数据转换为视图节点数据
     * @param {Array} nodeDatas
     */
    function nodeDataToVMNodeData(nodeDatas) {
        return nodeDatas.map((i, index) => {
            if (i.children) {
                i.children = nodeDataToVMNodeData(i.children);
            }
            Object.assign(i, {
                title: i.name || i.title,
                key: i.id,
                scopedSlots: { title: 'custom' },
                isFirst: index == 0 ? true : false,
                isLast: index == nodeDatas.length - 1 ? true : false
            });
            return i;
        })
    }

    /**
     * 树中查询节点
     * @returns {{
            node: item,
            pNode: tree
       }}
     */
    function queryNodeInTree(key, tree) {
        if (!tree.children) {
            return null;
        }
        if(tree.children.length==0){
            return null;
        }
        const item = tree.children.find(i => i.key == key);
        if (item) {
            return {
                node: item,
                pNode: tree
            };
        }
        const arr = tree.children.map(i => queryNodeInTree(key, i));
        return arr.find(i=>i!=null);
    }
</script>